<template>
    <div class="stock">
        <!-- 库存信息查询 -->
        <div class="header">
            <h3 class="blue-bg">库存查询</h3>
        </div>
        <div class="search">
            <div class="serch-content">
                <el-input placeholder="请输入您要查询的型号" v-model="partNumber" clearable class="input-with-select">
                    <el-button slot="prepend" type="primary">型号</el-button>
                </el-input>
                <el-button  icon="el-icon-search" type="primary" class="search-btn" @click="searchPar"></el-button>
                <el-upload
                    ref="uploadXlsx"
                    accept=""
                    action
                    :auto-upload="false"
                    :on-change="importData"
                    :show-file-list="false"
                    >
                    <el-button  type="primary" round>导入BOM查询</el-button>
                </el-upload>
            </div>
        </div>
        <div class="recommend" v-if="!isNumshow">
            <h2>为您推荐</h2>
            <mytable :config="tableconfig">
                <div slot="mytablebody">
                </div>
                <!-- 操作 -->
                <template v-slot:operation="{ data }">
                    <i class="el-icon-star-off" @click="getClollect(data)"></i>
                </template>
                 <!-- 包装 -->
                <template v-slot:packing="{ data }">
                    <p v-if="data.packing == 1" class="type-box">卷带(TR)</p>
                    <p v-if="data.packing == 2" class="type-box">Pack</p>
                </template>
                <!-- 库存所在地 -->
                <template v-slot:inventoryHome="{ data }">
                    <p v-if="data.inventoryHome == 1" class="type-box">中国大陆</p>
                    <p v-if="data.inventoryHome == 2" class="type-box">中国香港</p>
                </template>
            </mytable>
        </div>
        <div class="recommend" v-else>
            <div class="operation-btn">
                <el-button  type="primary">去询价</el-button>
                <el-button  type="primary">生成订单</el-button>
            </div>
            <mytable :config="tableconfig1">
                <div slot="mytablebody">
                </div>
                <!-- 收藏 -->
                <template v-slot:collect="{ data }">
                    <i class="el-icon-star-off" @click="getNumClollect(data)"></i>
                </template>
                <!-- 操作 -->
                <template v-slot:operation="{ data }">
                   <p class="price" @click="getPrice(data)">议价</p>
                </template>
                 <!-- 包装 -->
                <template v-slot:packing="{ data }">
                    <p v-if="data.packing == 1" class="type-box">卷带(TR)</p>
                    <p v-if="data.packing == 2" class="type-box">Pack</p>
                </template>
                <!-- 库存所在地 -->
                <template v-slot:inventoryHome="{ data }">
                    <p v-if="data.inventoryHome == 1" class="type-box">中国大陆</p>
                    <p v-if="data.inventoryHome == 2" class="type-box">中国香港</p>
                </template>
            </mytable>
        </div>
        <el-dialog title="确认" :visible.sync="dialogCollectVisible" class="submit-dialog">
            <div class="tit">
                确认收藏该型号
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogCollectVisible = false">取 消</el-button>
                <el-button type="primary" @click="getSumbit">确 定</el-button>
            </div>
        </el-dialog>
        <el-drawer
            title="议价申请"
            :before-close="handleClose"
            :visible.sync="dialog"
            direction="rtl"
            custom-class="demo-drawer"
            ref="drawer"
            size="35%"
            >
        <div class="demo-drawer__content">
            <div class="content-top">
                <h3>库存信息</h3>
                <el-card class="box-card">
                    <el-descriptions class="margin-top" :column="2">
                        <el-descriptions-item label="型号：">H1</el-descriptions-item>
                        <el-descriptions-item label="品牌：">KEMET</el-descriptions-item>
                        <el-descriptions-item label="数量：">1000</el-descriptions-item>
                        <el-descriptions-item label="批次：">22+</el-descriptions-item>
                        <el-descriptions-item label="封装：">XXXXXW5</el-descriptions-item>
                        <el-descriptions-item label="接受价：">10.000000</el-descriptions-item>
                        <el-descriptions-item label="币种：">人民币</el-descriptions-item>
                        <el-descriptions-item label="交货日期：">2022-11-11</el-descriptions-item>
                        <el-descriptions-item label="交货地：">国内</el-descriptions-item>
                        <el-descriptions-item label="包装：">卷带</el-descriptions-item>
                        <el-descriptions-item label="发票类型：">增值税专用发票</el-descriptions-item>
                    </el-descriptions>
                </el-card>
            </div>
            <h3>我的议价</h3>
            <el-card class="box-card">
                <el-form :model="form" ref="form" :rules="rules">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="议价价格：" :label-width="formLabelWidth" prop="price">
                                <el-input v-model="form.price" autocomplete="off" style="width:100%;" @keyup.native="form.price = form.price.replace(/[^\d]/g,'')"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="币种：" :label-width="formLabelWidth" prop="currency">
                                <el-select v-model="form.currency" placeholder="请选择币种" style="width:100%;">
                                    <el-option label="人民币" value="0"></el-option>
                                    <el-option label="美元" value="1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="议价数量：" :label-width="formLabelWidth" prop="count">
                                <el-input v-model="form.count" autocomplete="off" style="width:100%;" @keyup.native="form.count = form.count.replace(/[^\d]/g,'')"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="交货日期：" :label-width="formLabelWidth" prop="createDate">
                                <formDate :date="form.createDate" @getData="getDate"></formDate>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="交货地：" :label-width="formLabelWidth" prop="inventoryHome">
                                <el-select v-model="form.inventoryHome" placeholder="请选择币种" style="width:100%;">
                                    <el-option label="国内" value="0"></el-option>
                                    <el-option label="香港" value="1"></el-option>
                                </el-select>
                            </el-form-item>
                            
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="议价有效期：" :label-width="formLabelWidth" prop="date">
                                <formDate :date="form.date" @getData="getPriceDate"></formDate>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="备注：" :label-width="formLabelWidth" prop="remark">
                                <el-input v-model="form.remark" autocomplete="off" type="textarea"  style="width:100%;"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
            <div class="demo-drawer__footer">
                <el-button type="primary" @click="getFormsubmit('form')" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
                <el-button @click="cancelForm">取 消</el-button>
            </div>
        </div>
        </el-drawer>
    </div>
</template>
<script>
    import mytable from '@/components/table/index.vue';
    import formDate from '@/components/formDate/index.vue';
    import * as XLSX from 'xlsx';
    import JsZip from "jszip";
    import iconv  from "iconv-lite"
    import {uploadFile,configFileReader,arrayBufferToBase64,dataURLtoFile} from './index'
    export default{
        components:{
            mytable,
            formDate
        },
        data(){
            return{
                partNumber:'',
                tableconfig: {
                    loading: false,
                    isselection: false,
                    ispagination: false,
                    isfixed:true,
                    tabledata: [
                        {
                            operation:'',  
                            partNumber:'测试专用供应商有限公司',
                            brand:"CEC(中电熊猫)",
                            batch:'22+',
                            packages:'XXXW95',
                            packing:1,
                            inventoryHome:2,
                        }
                    ],
                    isindex: false,
                    thead: [
                    { sort: null, label: '操作', prop: 'operation', width: 50,type: 'slot' },
                    { sort: null, label: '型号', prop: 'partNumber',width: 150 },
                    { sort: null, label: '品牌', prop: 'brand', width: 150 },
                    { sort: null, label: '批次', prop: 'batch', },
                    { sort: null, label: '封装', prop: 'packages' },
                    { sort: null, label: '包装', prop: 'packing', width: 100 ,type: 'slot'},
                    { sort: null, label: '库存所在地', prop: 'inventoryHome',width: 100,type: 'slot'},   
                    ],
                    // checkedAll: false, //全选所有
                    checkedPage: false, //全选本页
                    currentpage: 1,
                    pagesize: 1,
                    total: 3,
                },
                tableconfig1: {
                    loading: false,
                    isselection: true,
                    ispagination: true,
                    isfixed:true,
                    tabledata: [
                        {
                            operation:'',  
                            partNumber:'测试专用供应商有限公司',
                            brand:"CEC(中电熊猫)",
                            batch:'22+',
                            packages:'XXXW95',
                            packing:1,
                            inventoryHome:2,
                        },
                        {
                            operation:'',  
                            partNumber:'测试专用供应商有限33公司',
                            brand:"CEC3(中电熊猫)",
                            batch:'232+',
                            packages:'XXXW95',
                            packing:1,
                            inventoryHome:2,
                        },
                        {
                            operation:'',  
                            partNumber:'测试专用供应商有限w33公司',
                            brand:"CEC3(中电熊猫)",
                            batch:'232+',
                            packages:'XXXW95',
                            packing:1,
                            inventoryHome:2,
                        }
                    ],
                    isindex: false,
                    thead: [
                    { sort: null, label: '收藏', prop: 'collect', width: 50,type: 'slot' },
                    { sort: null, label: '操作', prop: 'operation', width: 50,type: 'slot' },
                    { sort: null, label: '型号', prop: 'partNumber',width: 150 },
                    { sort: null, label: '品牌', prop: 'brand', width: 150 },
                    { sort: null, label: '批次', prop: 'batch', },
                    { sort: null, label: '封装', prop: 'packages' },
                    { sort: null, label: '包装', prop: 'packing', width: 100 ,type: 'slot'},
                    { sort: null, label: '库存所在地', prop: 'inventoryHome',width: 100,type: 'slot'},   
                    ],
                    // checkedAll: false, //全选所有
                    checkedPage: false, //全选本页
                    currentpage: 1,
                    pagesize: 1,
                    total: 3,
                },
                dialogCollectVisible:false,
                inventoryList:[],
                zipList: [],//压缩包解析前文件列表
                flagLength:'',//用于记录异步解读的条数
                upFlagSum:0,//用于计数当前解读的文件为第几条
                resultList:[],
                isNumshow:false,
                loading: false,
                dialog: false,
                form: {
                    price: '',
                    inventoryHome: '',
                    count: '',
                    createDate: '',
                    currency:'',
                    date: '',
                    remark: ''
                },
                rules: {
                    price: [
                        { required: true, message: '请输入议价价格', trigger: 'blur' },
                    ],
                    inventoryHome: [
                        { required: true, message: '请选择交货地', trigger: 'change' }
                    ],
                    count: [
                        { required: true, message: '请输入数量', trigger: 'blur' },
                    ],
                    createDate: [
                        {required: true, message: '请选择日期', trigger: 'change' }
                    ],
                    date: [
                        {required: true, message: '请选择日期', trigger: 'change' }
                    ],
                    currency: [
                        { required: true, message: '请选择币种', trigger: 'change' }
                    ],
                },
                formLabelWidth: '110px',
              
            }
        },
        methods:{
            getClollect(val){
                console.log(val);
                this.dialogCollectVisible = true;
            },
            getNumClollect(val){
                console.log(val);
                this.dialogCollectVisible = true;
            },
            getPrice(val){
                console.log(val,'433333333333');
                this.dialog = true;
            },
            getSumbit(){

            },
            getDate(date){
                this.form.createDate = date;
            },
            getPriceDate(date){
                this.form.date = date;
            },
            getFormsubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                      console.log(this.form,'this.formthis.form');
                        this.$refs.drawer.closeDrawer();
                    } else {
                        return false;
                    }
                });
            },
            searchPar(){
                console.log(this.partNumber,'444444');
                this.isNumshow = true;
            },
            importData(file, fileList){
                this.loading = true;
                this.inventoryList = [];
                console.log(file,fileList,'file wen');
                let testFile = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
                const extension = testFile === 'xlsx' || testFile === 'xls';
                const zipextension = testFile === 'xlsx' || testFile === 'xls'|| testFile === 'zip';
                let imgSize = Number(file.size / 1024 / 1024);
                if (!zipextension) {
                    this.loading =false;
                    this.$message({
                        message: '上传文件只能是xls/xlsx和zip文件！',
                        type: 'warning'
                    });
                    return false;
                }else{
                    if(extension){
                        if (imgSize > 5){
                        this.$message({
                            message: '文件大小超过5M，请上传ZIP文件！',
                            type: 'warning'
                        });
                        this.loading =false;
                        return false;
                        }else{
                        this.handleNumBatch(file);
                        }
                    }else{
                        this.zipXlsxUpload(file)
                    }
                }
                this.partNumber = file.name;
            },
            handleNumBatch(file){
                const f = file.raw;
                // 用 FileReader 来读取
                let reader = new FileReader()
                // 重写 FileReader 上的 readAsBinaryString 方法
                FileReader.prototype.readAsBinaryString = f => {
                    let binary = ''
                    let wb // 读取完成的数据
                    let outdata // 你需要的数据
                    let reader = new FileReader()
                    reader.onload = e => {
                    // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
                    let bytes = new Uint8Array(reader.result)
                    let length = bytes.byteLength
                    for (let i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i])
                    }
                    // 接下来就是xlsx了，具体可看api
                    wb = XLSX.read(binary, {
                        type: 'binary',
                        cellDates: false
                    })
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
                    console.log(outdata,'outdataoutdataoutdataoutdata');
                    const result = this.generateParam(outdata);
                    console.log('result--', result);
                    this.loading = false;
                    this.inventoryList= result;
                    // let valLength  = [];
                    // this.inventoryList.map(item=>{
                    //     if(item.count != undefined &&  this.reg.test(item.count) 
                    //     || item.batch != undefined && this.batchReg.test(item.batch) 
                    //     || item.moq != undefined && this.reg.test(item.moq) 
                    //     || item.mpq != undefined && this.reg.test(item.mpq) 
                    //     ||item.unitPrice != undefined && !this.priceReg.test((item.unitPrice*1).toFixed(6))
                    //     || item.currency != undefined && item.currency != '人民币'&& item.currency != '美金' 
                    //     || item.inventoryHome != undefined && item.inventoryHome != '中国大陆' && item.inventoryHome != '中国香港' 
                    //     ){
                    //         valLength.push(item)
                    //     }
                    // })
                    // if(valLength.length > 0){
                    //     this.$message.error('您的字段输入有误，请修改')
                    // }
                    }
                    reader.readAsArrayBuffer(f)
                }
                reader.readAsBinaryString(f)
            },
            //3.上传ZIP压缩包，读取并处理其中XLSX数据相关方法--
            zipXlsxUpload(file) {
                var zip = new JsZip();
                //解压zip
                zip.loadAsync(file.raw, {
                    //解决文件名乱码问题
                    decodeFileName: function (bytes) {
                        return iconv.decode(bytes, 'gbk');
                    }
                    }).then((file) => {
                        //excel文件列表
                        this.zipList = file.files;
                        //摘除非excel数据
                        let arr =[];
                        for (let key in this.zipList) {
                            if (/\.(xlsx)$/.test(key)) { 
                                arr.push(this.zipList[key])
                            }
                        }
                        const asyncReaderList = arr.filter((r) => !r.dir && r.name.indexOf("MACOSX") === -1)
                        //因为id只存在于文件名，所以解析前进行需要的数据拼接
                        let asyncReaderListCopy = [];
                        asyncReaderList.forEach(item =>{
                        let obj ={
                            // 员工Id格式：文件夹名/12345678姓名.xlsx
                            value : zip.file(item.name).async("uint8array"),
                            name : item.name
                        }
                        asyncReaderListCopy.push(obj)
                        })
                        console.log(asyncReaderListCopy,'asyncReaderListCopy');
                        //用于reader.onload异步调用计数
                        this.flagLength = asyncReaderListCopy.length;
                        asyncReaderListCopy.forEach(zipFile=>{
                            //用于取到promise中的数据
                            Promise.resolve(zipFile.value).then((item)=>{
                                //1>用于附件上传，预览功能
                                let base =  arrayBufferToBase64(item);
                                // Base64 转 File 对象
                                const result = dataURLtoFile(base, zipFile.name);
                                console.log(result,'最终解压后的File对象')
                                this.resultList.push(result);
                                //2>用于读取每个excel页签里的内容
                                const reader = new FileReader(zipFile.name);
                                console.log(reader,'reader.onload');
                                reader.onload = (e) => {
                                this.onReaderLoad(e);
                                };  
                                reader.readAsBinaryString(new Blob([item]));
                            })
                        })
                }).catch((err) => {
                    // 请求失败
                    this.$message.error(err)
                });   
            },
            //4取出XLSX文件数据
            onReaderLoad(e) {
                this.inventoryList =[];
                let excelData = e.target.result;
                //  //设置时间读取格式1>.{ type: "binary" ,cellDates:true,cellText:false}
                const workbook = XLSX.read(excelData, { type: "binary" ,cellDates:true,cellText:false});
                console.log(workbook,'workbookworkbookworkbook');
                if (workbook.Sheets) {
                    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                    //设置时间读取格式2>.{ raw: false,dateNF: 'yyyy/mm/dd'}
                    const data = XLSX.utils.sheet_to_json(worksheet);
                    console.log(data);
                    const result = this.generateParam(data);
                    this.loading = false;
                    this.inventoryList = result; 
                }
                let valLength  = [];
                // this.inventoryList.map(item=>{
                //     if(item.count != undefined &&  this.reg.test(item.count) 
                //         || item.batch != undefined && this.batchReg.test(item.batch) 
                //         || item.moq != undefined && this.reg.test(item.moq) 
                //         || item.mpq != undefined && this.reg.test(item.mpq) 
                //         ||item.unitPrice != undefined && !this.priceReg.test((item.unitPrice*1).toFixed(6))
                //         || item.currency != undefined && item.currency != '人民币'&& item.currency != '美金' 
                //         || item.inventoryHome != undefined && item.inventoryHome != '中国大陆' && item.inventoryHome != '中国香港' 
                //     ){
                //         valLength.push(item)
                //     }
                // })
                //     console.log(valLength,'valLengthvalLengthvalLength');
                //     if(valLength.length > 0){
                //     this.$message.error('您的字段输入有误，请修改');
                // }
            },
            // 生成导入参数
            generateParam(data) {
                const params = []
                // 这里根据实际表格 title 值、接口参数值，灵活变化
                const parse = {
                    '品牌*': 'brand',
                    '型号*': 'partNumber',
                    '批次*': 'batch',
                    '数量*': 'count',
                    币种: 'currency',
                    库存所在地: 'inventoryHome',
                    MOQ: 'moq',
                    MPQ: 'mpq',
                    封装: 'packages',
                    包装: 'packing',
                    单价: 'unitPrice',
                }
                data.forEach(item => {
                    let obj = {}
                    const keys = Object.keys(parse)
                    const itemKeys = Object.keys(item)
                    itemKeys.forEach(key => {
                    const val = item[key]
                    if (keys.includes(key)) {
                        obj[parse[key]] = val
                    }
                    })
                    params.push(obj)
                })
                return params
            },
            handleClose(done) {
                if (this.loading) {
                    return;
                }
                console.log(done,'donedone');
                done();
                this.$refs.form.resetFields();
                this.form.createDate = '';
                this.form.date = '';
            },
            cancelForm() {
                this.loading = false;
                this.dialog = false;
                this.$refs.form.resetFields();
                // clearTimeout(this.timer);
            }
        }
    }
</script>
<style lang="scss" scoped>
    .stock{
        width: 100%;
        padding: 20px 0 0;
        // background-color: #fff;
        font-size: 16px;
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            h3 {
                font-weight: bold;
            }
        }
        .blue-bg::before {
            content: ' ';
            width: 8px;
            height: 20px;
            background: #0782eb;
            display: inline-block;
            vertical-align: bottom;
            margin: 0px 5px;
        }
        .search{
            width: 100%;
            height: 100px;
            background-color: #eee;
            margin: 20px 0;
            padding-top: 35px;
            .serch-content{
                display: flex;
                align-items: center;
                justify-content: center;
                .search-btn{
                    margin: 0 20px;
                }
            }
            .el-input {
                width: 20%;
            }
        }
        .recommend{
            background: #fff;
            padding: 20px 20px 10px;
            h2{
                font-weight: 600;
                color: #0782eb;
                text-align: center;
                margin-bottom: 10px;
            }
            .price{
                color: #0782eb;
                text-align: center;
                cursor: pointer;
            }
        }
        .submit-dialog{
            width: 35%;
            .tit{
                font-size: 16px;
                font-weight: 600;
                line-height: 32px;
                text-align: center;
            }
            .dialog-footer{
                text-align: center;
            }
        }
        .demo-drawer__content{
            padding: 0 20px;
            h3{
                line-height: 32px;
                margin-bottom: 5px;
            }
            .content-top{
                margin-bottom: 20px;
            }
            .demo-drawer__footer{
                text-align: center;
                margin: 30px 0;
            }
        }
        
    }
</style>